import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
import {
  listNormalStoreSpokesmanWithUsersByStoreID,
  updateStoreSpokesman,
} from "../../service/storeSpokesmanService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
const router = createStoreApiMWRouter();

// 获取门店代言人列表
router.get("/sto/:storeId/spokesmans", pageMW, async (ctx: AppCTX, next) => {
  const { storeId } = ctx.params;
  let { keyword } = ctx.query;
  const { userId, limit, offset, ts } = ctx;

  const { total, items } = await listNormalStoreSpokesmanWithUsersByStoreID(
    { storeId, keyword },
    {
      limit,
      offset,
      ts,
    }
  );
  const followerRecentNews = await listAggsToUserRecentNewses(
    items.map((it) => it.userId)
  );
  const recentNewsMap = reduceToObject(
    followerRecentNews,
    (o) => o.userId,
    (o) => o.latestTime
  );

  ctx.body = {
    total,
    rows: items.map((it) => ({
      recentNews: recentNewsMap[it.userId],
      ...it,
    })),
  };
});

// 备注门店代言人名称
router.put(
  "/sto/:storeId/spokesman/alias/:storeSpokesmanId",
  async (ctx: AppCTX, next) => {
    const { storeId, storeSpokesmanId } = ctx.params;
    const { aliasName } = ctx.request.body;
    const { userId } = ctx;
    //1 userId(操作人不是代言人),报错

    const storeSpokesman = await updateStoreSpokesman({
      storeSpokesmanId,
      aliasName,
    });

    ctx.body = {
      ...storeSpokesman,
    };
  }
);

export default router;
